package com.chookss;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;

import com.chookss.base.StaticClass;
import com.chookss.base.X5WebView;
import com.chookss.home.tuwen.PublishTuwensActivity;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.NavigationTools;
import com.chookss.tools.PermissionSpUtils;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.XJson;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.OkGoUtil;
import com.chookss.tools.okgoconfig.callback.JsonCallback;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.wxapi.ShareActivity;
import com.google.gson.reflect.TypeToken;
import com.johnrambo.ktea.common.klogutil.KLog;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.lvgroup.hospital.base.BaseAct;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.AttachPopupView;
import com.lxj.xpopup.enums.PopupPosition;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.lzy.okgo.model.Response;
import com.tencent.smtt.export.external.extension.interfaces.IX5WebViewExtension;
import com.tencent.smtt.export.external.interfaces.IX5WebChromeClient;
import com.tencent.smtt.export.external.interfaces.SslError;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.Nullable;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import pl.droidsonroids.gif.GifDrawable;
import pl.droidsonroids.gif.GifImageView;

public class WebCommonActivity extends BaseAct {
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.flTop)
    FrameLayout flTop;
    @BindView(R.id.webView)
    X5WebView webView;
    @BindView(R.id.ivBack)
    ImageView ivBack;
    @BindView(R.id.tvRight)
    TextView tvRight;
    @BindView(R.id.llBottom)
    LinearLayout llBottom;
    @BindView(R.id.tvSure)
    TextView tvSure;
    @BindView(R.id.rlRight)
    LinearLayout rlRight;
    @BindView(R.id.ivRight)
    ImageView ivRight;
    @BindView(R.id.collectLl)
    LinearLayout collectLl;
    @BindView(R.id.ivCollect)
    ImageView ivCollect;
    @BindView(R.id.gif_view)
    GifImageView gifView;
    private GifDrawable gifDrawable = null;
    private String url, title, userName, createEmployeeName;
    private boolean isPress = false;//是否可以查看个人能力分析
    private boolean isFull = false;//是否全屏
    private boolean isPersonalAbility = false;//是否个人能力分析页面  一定要全屏的
    /**
     * Wechat pay scheme ，用于唤醒微信支付
     */
    public static final String WECHAT_PAY_SCHEME = "weixin://wap/pay?";
    public static final String TAOBAO_SCHEME = "taobao";
    /**
     * 支付宝
     */
    public static final String ALIPAYS_SCHEME = "alipays://";
    private String waterMark;//是否要水印
    private boolean isShare = false;//是否要分享的页面
    private boolean isCollect = false;//是否收藏
    private int isTuwen = 0;//1图文是预览页面点击编辑回到发布页2预览可编辑点击跳转发布页3是图文详情
    private String newsTitle, newsContent, resourceId, newsPic;//新闻和图文分享所需
    AttachPopupView attachPopupView;//图文详情弹窗所用
    private String lpFlag = "";//0禁止1正常
    private boolean isShowFull = false;//是否全屏播放视频
    View myVideoView;
    IX5WebChromeClient.CustomViewCallback callback;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_view);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        //网页中的视频，上屏幕的时候，可能出现闪烁的情况
        getWindow().setFormat(PixelFormat.TRANSLUCENT);
        try {
            if (Integer.parseInt(android.os.Build.VERSION.SDK) >= 11) {
                getWindow()
                        .setFlags(
                                android.view.WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
                                android.view.WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
            }
        } catch (Exception e) {
        }
        url = getIntent().getStringExtra("url");
        isTuwen = getIntent().getIntExtra("isTuwen", 0);
        isShare = getIntent().getBooleanExtra("isShare", false);
        title = getIntent().getStringExtra("title");
        resourceId = getIntent().getStringExtra("resourceId");
        newsTitle = getIntent().getStringExtra("newsTitle");
        newsContent = getIntent().getStringExtra("newsContent");
        newsPic = getIntent().getStringExtra("picUrl");
        waterMark = getIntent().getStringExtra("waterMark");
        userName = getIntent().getStringExtra("userName");
        createEmployeeName = getIntent().getStringExtra("createEmployeeName");
        isFull = getIntent().getBooleanExtra("isFull", false);
        isPersonalAbility = getIntent().getBooleanExtra("isPersonalAbility", false);
        if (!Utils.isNull(waterMark)) {
            NavigationTools.setWaterMark(this, waterMark);
            lpFlag = new ShareUtils().getString(this, StaticClass.LP_FLAG, "1");
            //禁止截屏
            if ("0".equals(lpFlag)) {
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
            }
        }
        if (isPersonalAbility) {
            setNoFull();
            setPersonalAbility();
            NavigationTools.saveUseRecord(this, "1", "08");
        } else if (isFull) {
            setFull();
            showLoading();
        } else {
            setNoFull();
            showLoading();
        }
        if (isTuwen > 0) {
            //是图文详情
            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) ivRight.getLayoutParams();
            if (isTuwen == 1) {
                layoutParams.height = Utils.dip2px(this, (float) 15.5);
                layoutParams.width = Utils.dip2px(this, (float) 21.5);
                ivRight.setBackgroundResource(R.drawable.icon_close_43);
                ivRight.setLayoutParams(layoutParams);
            } else if (isTuwen == 2) {
                ivRight.setVisibility(View.GONE);
                tvRight.setVisibility(View.VISIBLE);
                tvRight.setText("编辑");
            } else {
                layoutParams.height = Utils.dip2px(this, (float) 4.5);
                layoutParams.width = Utils.dip2px(this, 20);
                ivRight.setBackgroundResource(R.drawable.icon_more_48);
                ivRight.setLayoutParams(layoutParams);
                collectLl.setVisibility(View.VISIBLE);
                getTuwenStatus();
            }
            rlRight.setVisibility(View.VISIBLE);
        } else if (isShare) {
            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) ivRight.getLayoutParams();
            layoutParams.height = Utils.dip2px(this, 25);
            layoutParams.width = Utils.dip2px(this, 25);
            ivRight.setLayoutParams(layoutParams);
            ivRight.setBackgroundResource(R.drawable.icon_share);
            rlRight.setVisibility(View.VISIBLE);
        } else {
            ivRight.setBackgroundResource(R.drawable.icon_wenh_42);
        }
        collectLl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isCollect) {
                    collectTuwen("0");
                    isCollect = false;
                    ivCollect.setBackgroundResource(R.drawable.icon_collect_48);
                } else {
                    collectTuwen("1");
                    isCollect = true;
                    ivCollect.setBackgroundResource(R.drawable.icon_yellow_collect);
                }
            }
        });
        rlRight.setOnClickListener(v -> {
            if (isTuwen > 0) {
                //是图文详情
                if (isTuwen == 1) {
                    finish();
                } else if (isTuwen == 2) {
                    if (PermissionSpUtils.getBoolean(this, "16", false)) {
                        Intent intent = new Intent(this, PublishTuwensActivity.class);
                        intent.putExtra("mainCode", resourceId);
                        startActivity(intent);
                    } else {
                        MyToast.show("管理员已关闭图文发布功能");
                    }
                    finish();
                } else {
                    attachPopupView = new XPopup.Builder(this)
                            .hasShadowBg(false)
                            .isClickThrough(true)
                            .popupPosition(PopupPosition.Bottom) //手动指定弹窗的位置
                            .atView(ivRight)  // 依附于所点击的View，内部会自动判断在上方或者下方显示
                            .asAttachList(new String[]{"分享", "发至新闻"},
                                    new int[]{R.drawable.icon_send_40, R.drawable.icon_share_40},
                                    new OnSelectListener() {
                                        @Override
                                        public void onSelect(int position, String text) {
                                            if (position == 0) {
                                                Intent intent = new Intent(WebCommonActivity.this, ShareActivity.class);
                                                intent.putExtra("title", newsTitle);
                                                intent.putExtra("createEmployeeName", createEmployeeName);
                                                intent.putExtra("content", newsContent);
                                                intent.putExtra("resourceId", resourceId);
                                                intent.putExtra("picUrl", newsPic);
                                                intent.putExtra("resourceType", 5);
                                                startActivity(intent);
                                            } else {
                                                getTuwenData();
                                            }
                                        }
                                    }, 0, 0, Gravity.LEFT);
                    ;
                    attachPopupView.show();
                }
            } else if (isShare) {
                Intent intent = new Intent(this, ShareActivity.class);
                intent.putExtra("title", newsTitle);
                intent.putExtra("createEmployeeName", createEmployeeName);
                intent.putExtra("content", newsContent);
                intent.putExtra("resourceId", resourceId);
                intent.putExtra("picUrl", newsPic);
                intent.putExtra("resourceType", 4);
                startActivity(intent);
            } else {
                String url = NavigationTools.getAllUrl2(WebCommonActivity.this, Urls.webBaseUrl + "capacityAnalysis.html#/relation?");
                webView.loadUrl(url);
            }

        });
        webView.loadUrl(url);
        configPlaySetting();
        KLog.i(url);
        webView.setWebChromeClient(new WebChromeClient() {
            //For Android  >= 5.0
            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
                return true;
            }

            //For Android  >= 4.1
            public void openFileChooser(ValueCallback<Uri> valueCallback, String acceptType, String capture) {
            }

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
            }

            @Override
            public void onReceivedTitle(WebView webView, String s) {
                super.onReceivedTitle(webView, s);
                KLog.i(s + "---s" + webView.getTitle());
            }


            /**
             * 全屏播放配置
             */
            @Override
            public void onShowCustomView(View view,
                                         IX5WebChromeClient.CustomViewCallback customViewCallback) {
                //此处是把webview的父布局替换为view，此view是全屏播放时候的界面（tbs的默认实现）
                ViewGroup viewGroup = (ViewGroup) webView.getParent();
                viewGroup.removeView(webView);
                // 设置背景色为黑色
                view.setBackgroundColor(getResources().getColor(R.color.black));
                view.setMinimumHeight(viewGroup.getHeight());
                viewGroup.addView(view);
                myVideoView = view;
                callback = customViewCallback;
                //全屏模式
                getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                        WindowManager.LayoutParams.FLAG_FULLSCREEN);
                isShowFull = true;
            }

            @Override
            public void onHideCustomView() {
                //退出全屏
                quitFullScreen();
            }
        });
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
                // TODO Auto-generated method stub
                return super.shouldOverrideKeyEvent(view, event);
            }

            @Override
            public boolean shouldOverrideUrlLoading(final WebView view,
                                                    final String url) {
                if (url.startsWith("mbspay:")) {
                    PackageManager pm = getPackageManager();
                    Intent checkIntent = pm.getLaunchIntentForPackage("com.chinamworld.main");
                    if (checkIntent != null) {
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                        //防止打开两次webcommon
                        startActivity(intent);
                    }
                    return true;
                }
                // ------  对alipays:相关的scheme处理 -------
                if (url.startsWith(ALIPAYS_SCHEME) || url.startsWith("alipay")) {
                    try {
                        startActivity(new Intent("android.intent.action.VIEW", Uri.parse(url)));
                    } catch (Exception e) {
                        new AlertDialog.Builder(WebCommonActivity.this)
                                .setMessage("未检测到支付宝客户端，请安装后重试。")
                                .setPositiveButton("立即安装", new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        Uri alipayUrl = Uri.parse("https://d.alipay.com");
                                        startActivity(new Intent("android.intent.action.VIEW", alipayUrl));
                                    }
                                }).setNegativeButton("取消", null).show();
                    }
                    return true;
                } else if (url.startsWith(WECHAT_PAY_SCHEME)) {
                    try {
                        startActivity(new Intent("android.intent.action.VIEW", Uri.parse(url)));
                    } catch (Exception e) {
                        new AlertDialog.Builder(WebCommonActivity.this)
                                .setMessage("未检测到微信客户端，请安装后重试。")
                                .setPositiveButton("立即安装", new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        Uri alipayUrl = Uri.parse("https://sj.qq.com/myapp/detail.htm?apkName=com.tencent.mm&apkCode=1400");
                                        startActivity(new Intent("android.intent.action.VIEW", alipayUrl));
                                    }
                                }).setNegativeButton("取消", null).show();
                    }
                    return true;
                } else if (url.startsWith(TAOBAO_SCHEME)) {
                    try {
                        startActivity(new Intent("android.intent.action.VIEW", Uri.parse(url)));
                    } catch (Exception e) {
                        new AlertDialog.Builder(WebCommonActivity.this)
                                .setMessage("未检测到淘宝客户端，请安装后重试。")
                                .setPositiveButton("立即安装", new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        Uri taobaoUrl = Uri.parse("https://sj.qq.com/myapp/detail.htm?apkName=com.taobao.taobao");
                                        startActivity(new Intent("android.intent.action.VIEW", taobaoUrl));
                                    }
                                }).setNegativeButton("取消", null).show();
                    }
                    return true;
                }
                return super.shouldOverrideUrlLoading(webView, url);
            }// 重写点击动作,用webview载入

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
            }

            @Override
            public void onReceivedSslError(WebView webView, SslErrorHandler sslErrorHandler, SslError sslError) {
                // 不要使用super，否则有些手机访问不了，因为包含了一条 handler.cancel()
                // super.onReceivedSslError(view, handler, error);
                // 接受所有网站的证书，忽略SSL错误，执行访问网页
                sslErrorHandler.proceed();
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                if (tvTitle == null || rlRight == null || view == null) {
                    return;
                }
                try {
                    dismissLoading();
                    KLog.i("------------onPageFinished");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                KLog.i(view.getTitle() + "-----" + view.getUrl());
                if (view.getUrl().contains("capacityAnalysis.html#/capacity")) {

                    if (Utils.isNull(userName)) {
                        tvTitle.setText("个人能力分析");
                    } else {
                        tvTitle.setText(userName + "的能力分析");
                    }
                    rlRight.setVisibility(View.GONE);
                } else if (view.getUrl().contains("capacityAnalysis.html#/grad")) {
                    //成长历程
                    tvTitle.setText("段位");
                    rlRight.setVisibility(View.VISIBLE);
                } else if (view.getUrl().contains("capacityAnalysis.html#/relation")) {
                    //成长历程
                    tvTitle.setText("关系");
                    rlRight.setVisibility(View.GONE);
                } else if (view.getUrl().contains("capacityAnalysis.html#/detail")) {
                    //成长历程
                    tvTitle.setText("明细");
                    rlRight.setVisibility(View.GONE);
                }
            }

        });
    }

    private void setFull() {
        //设置全屏
        initState2();
        ivBack.setImageResource(R.mipmap.icon_back);
        int statusBarHeight = Utils.getStatusBarHeight(this);
        RelativeLayout.LayoutParams topAllParams = (RelativeLayout.LayoutParams) flTop.getLayoutParams();
        topAllParams.setMargins(0, statusBarHeight, 0, 0);
        flTop.setLayoutParams(topAllParams);
        flTop.setBackgroundColor(getResources().getColor(R.color.transparent));
    }

    private void setNoFull() {
        //状态栏原生控制
        initState();
        if (ivBack == null) {
            return;
        }
        ivBack.setImageResource(R.drawable.icon_back_black);
        int statusBarHeight = Utils.getStatusBarHeight(this);
        RelativeLayout.LayoutParams webViewAllParams = (RelativeLayout.LayoutParams) webView.getLayoutParams();
        webViewAllParams.setMargins(0, statusBarHeight + Utils.dip2px(this, 44), 0, 0);
        webView.setLayoutParams(webViewAllParams);
        RelativeLayout.LayoutParams topAllParams = (RelativeLayout.LayoutParams) flTop.getLayoutParams();
        topAllParams.setMargins(0, statusBarHeight, 0, 0);
        flTop.setLayoutParams(topAllParams);
        flTop.setBackgroundColor(getResources().getColor(R.color.white));
        if (Utils.isNull(title)) {
            tvTitle.setText("详情");
        } else {
            tvTitle.setText(title);
        }
    }

    private void setPersonalAbility() {
        try {
            llBottom.setVisibility(View.VISIBLE);
            gifDrawable = new GifDrawable(getResources(), R.drawable.grnl_gif);
            gifDrawable.setLoopCount(1);
            gifView.setBackground(gifDrawable);
            KLog.i(gifDrawable.getDuration() + "----");
            Observable.timer(gifDrawable.getDuration() - 1000, TimeUnit.MILLISECONDS).observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer<Long>() {
                        @Override
                        public void accept(Long aLong) {
                            if (tvSure != null) {
                                tvSure.setPressed(true);
                                isPress = true;
                            }
                        }
                    });
            tvSure.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (isPress) {
                        llBottom.setVisibility(View.GONE);
                    } else {
                        MyToast.show("个人能力分析中");
                    }


                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void goBack() {
        //按下返回键或者左上角返回箭头的操作

        if (isShowFull) {
            quitFullScreen();
            return;
        } else if (null == webView.getUrl()) {
            finish();
        }
        if (null == webView) return;
        if (webView.canGoBack()) {
            webView.goBack();
        } else {
            finish();
        }

    }

    private void configPlaySetting() {
//        开启X5全屏播放模式
        Bundle data = new Bundle();
        data.putBoolean("standardFullScreen", true);// true表示标准全屏，false表示X5全屏；不设置默认false，
        data.putBoolean("supportLiteWnd", false);// false：关闭小窗；true：开启小窗；不设置默认true，
        data.putInt("DefaultVideoScreen", 1);// 1：以页面内开始播放，2：以全屏开始播放；不设置默认：1
        IX5WebViewExtension x5WebViewExtension = webView.getX5WebViewExtension();
        if (null != x5WebViewExtension) {
            x5WebViewExtension.invokeMiscMethod("setVideoParams",
                    data);
        }
    }

    /**
     * 退出全屏
     */
    private void quitFullScreen() {
        // 声明当前屏幕状态的参数并获取
        try {
            isShowFull = false;
            if (callback != null) {
                callback.onCustomViewHidden();
                callback = null;
            }
            if (myVideoView != null) {
                ViewGroup viewGroup = (ViewGroup) myVideoView.getParent();
                viewGroup.removeView(myVideoView);
                viewGroup.addView(webView);
            }
            final WindowManager.LayoutParams attrs = getWindow().getAttributes();
            attrs.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
            getWindow().setAttributes(attrs);
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnClick(R.id.ivBack)
    public void onClick() {
        goBack();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getMap() != null) {
            Map<String, String> map = messageEvent.getMap();

        } else {
            String msg = messageEvent.getMessage();
            if (Utils.isNull(msg)) {
                return;
            }
            if (msg.equals("Web_Close")) {
                finish();
            } else if (msg.equals("Web_Cancel_dialog")) {
                dismissLoading();
            }
        }
    }

    private void getTuwenData() {
        //先获取图文是否可以分享
        Map<String, String> map = new HashMap<>();
        map.put("code", resourceId);
        map.put("type", "4");
        MyHttpRequest.getRequest(Urls.selsectShareFlag, this, SignUtils2.makeSignStr(map), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                dismissLoading();
                try {
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    if ("200".equals(jsonObject.getString("code"))) {
                        JSONObject jsonObject1 = jsonObject.getJSONObject("data");
                        uploadTuwen(jsonObject1.getString("shareFlag"));
                    } else {
                        if (jsonObject.getString("code").startsWith("400")) {
                            OkGoUtil.onErrorIntent(jsonObject.getString("code"), jsonObject.getString("msg"));
                        } else {
                            uploadTuwen("1");
                        }

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    uploadTuwen("1");
                }
            }
        });
    }

    private void getTuwenStatus() {
        //先获取图文是否可以分享
        Map<String, String> map = new HashMap<>();
        map.put("collectId", resourceId);
        map.put("collectType", "5");
        MyHttpRequest.getRequest(Urls.getCollectFlag, this, SignUtils2.makeSignStr(map), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                dismissLoading();
                try {
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    if ("200".equals(jsonObject.getString("code"))) {
                        if (jsonObject.getString("data").equals("1")) {
                            isCollect = true;
                            ivCollect.setBackgroundResource(R.drawable.icon_yellow_collect);
                        } else {
                            isCollect = false;
                            ivCollect.setBackgroundResource(R.drawable.icon_collect_48);
                        }
                    } else {
                        if (jsonObject.getString("code").startsWith("400")) {
                            OkGoUtil.onErrorIntent(jsonObject.getString("code"), jsonObject.getString("msg"));
                        } else {
                            MyToast.show(jsonObject.getString("msg"));
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void collectTuwen(String type) {
        Map<String, String> map = new HashMap<>();
        map.put("collectId", resourceId);
        map.put("collectStatus", type);
        map.put("collectType", "5"); // 3:资料库 4：图库 5：图文
        MyHttpRequest.getDefault().postRequest(new TypeToken<LzyResponse<String>>() {
        }.getType(), null, Urls.toCollect, SignUtils2.makeSignStr(map), false, new ObserverCallback<String>() {
            @Override
            public void onSuccess(String data) {
                if (type.equals("0")) {
                    MyToast.show("取消收藏");
                } else {
                    MyToast.show("收藏成功");
                }
                EventBus.getDefault().post(new MyEvent("tuwenRefresh"));
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void uploadTuwen(String shareFlag) {
        //发至新闻
        Map<String, Object> map = new HashMap<>();
        map.put("quoteCode", resourceId);
        map.put("quoteFlag", "1");
        map.put("shareFlag", shareFlag);
        MyHttpRequest.postRequestJson(Urls.addNews, this, XJson.mapToJObj(map).toString(), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                try {
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    if ("200".equals(jsonObject.getString("code"))) {
                        EventBus.getDefault().post(new MyEvent("RefreshNews"));
                        MyToast.show("新闻发布成功");
                    } else {
                        if (jsonObject.getString("code").startsWith("400")) {
                            OkGoUtil.onErrorIntent(jsonObject.getString("code"), jsonObject.getString("msg"));
                        } else {
                            MyToast.show(jsonObject.getString("msg"));
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    MyToast.show("新闻发布失败，请稍后重试");
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (gifDrawable != null) {
            gifDrawable.recycle();
        }
    }


}
